package com.example.demo.controller;

import java.io.IOException;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import jakarta.annotation.Resource;

@RestController
@RequestMapping("/product")
public class ProductController {

    private final static String INDEX_NAME = "product";
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询
     */
    @RequestMapping("/query/1")
    public String query1() {

        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        // 使用搜索条件构造器，构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //查询条件，使用QueryBuilders 工具类，来实现

        // QueryBuilders.termQuery 精确查询
        //        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("userName", "郑军2");
        MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("蓝牙 指纹 双卡", "title", "intro");

        // QueryBuilders.matchAllQuery 匹配所有
        //		MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery();

        sourceBuilder.query(queryBuilder);

        // 分页
        sourceBuilder.from(0); // 默认 0
        sourceBuilder.size(2); // 默认 10

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder() //
            .field("title") //
            .field("intro") //
            .preTags("<em>") //
            .postTags("</em>") //
        ;
        sourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 处理查询结果
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, Object> source = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            // 处理高亮字段
            HighlightField titleField = highlightFields.get("title");
            if (titleField != null) {
                Text[] fragments = titleField.fragments();
                StringBuilder highlightedTitle = new StringBuilder();
                for (Text fragment : fragments) {
                    highlightedTitle.append(fragment);
                }
                // 获取高亮后的标题
                String highlightedTitleString = highlightedTitle.toString();
                // 使用高亮后的标题替换原始的标题
                source.put("title", highlightedTitleString);
            }

            HighlightField introField = highlightFields.get("intro");
            if (introField != null) {
                Text[] fragments = introField.fragments();
                StringBuilder highlightedIntro = new StringBuilder();
                for (Text fragment : fragments) {
                    highlightedIntro.append(fragment);
                }
                // 获取高亮后的介绍
                String highlightedIntroString = highlightedIntro.toString();
                // 使用高亮后的介绍替换原始的介绍
                source.put("intro", highlightedIntroString);
            }

            // 处理每个文档的结果
            System.out.println(source);
        }

        return JSON.toJSONString(searchResponse.getHits());
    }

}
